package filter.script.pre

import com.homedo.microservice.open.service.gateway.zuul.conf.DomainConf
import com.homedo.microservice.open.service.gateway.zuul.constant.ZuulConstant
import com.netflix.config.DynamicPropertyFactory
import com.netflix.config.DynamicStringProperty
import com.netflix.zuul.ZuulFilter
import com.netflix.zuul.constants.ZuulConstants
import com.netflix.zuul.context.Debug
import com.netflix.zuul.context.RequestContext
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.http.HttpServletRequest

public class DomainPreFilter extends ZuulFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(DomainPreFilter.class);

    @Override
    String filterType() {
        return "pre"
    }

    @Override
    int filterOrder() {
        return -1000
    }

    @Override
    boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();

        Boolean isAccessedRouteDomainFilter = requestContext.get(ZuulConstant.ZUUL_IS_ACCESSED_ROUTE_DOMAIN_FILTER);
        if (isAccessedRouteDomainFilter != null && isAccessedRouteDomainFilter) {
            return false;
        }

        String domain = requestContext.getRequest().getServerName();
        boolean inRouteDomainList = DomainConf.getInstance().getConfs().containsKey(domain);

        Debug.addRequestDebug("经过DomainPreFilter:[当前域名是:{},是否在域名过滤列表中:" + domain + "," + inRouteDomainList + "]");
//        LOGGER.info("[当前域名是:{},是否在域名过滤列表中:{}]", domain, inRouteDomainList);

        return inRouteDomainList;
    }

    @Override
    Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        String domain = requestContext.getRequest().getServerName();
        String routeAddPrefix = requestContext.get(ZuulConstant.ZUUL_ROUTE_ADD_PREFIX);
        if (routeAddPrefix != null && routeAddPrefix.length() > 0) {
            routeAddPrefix = routeAddPrefix + ZuulConstant.ZUUL_ROUTE_ADD_PREFIX_SPLIT + domain;
        } else {
            routeAddPrefix = domain;
        }

        Debug.addRequestDebug("经过DomainPreFilter:[通过域名过滤配置，添加转发路径前缀为:" + routeAddPrefix + "]");

//        if (requestContext.debugRequest()) {
//            LOGGER.info("[通过域名过滤配置，添加转发路径前缀为:{}]", routeAddPrefix);
//        }

        requestContext.put(ZuulConstant.ZUUL_ROUTE_ADD_PREFIX, routeAddPrefix);
        requestContext.put(ZuulConstant.ZUUL_IS_ACCESSED_ROUTE_DOMAIN_FILTER, true);
        return Boolean.TRUE;
    }

}
